package com.colin.util.util;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author zhaolz
 * @date 2022/3/23 12:15
 */
public class OssUtil {

    private static final Logger logger = LoggerFactory.getLogger(OssUtil.class);

    /**
     * yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
     */
    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    /**
     * 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
     */
    private static String accessKeyId = "LTAI5GLsvefUouo4";
    /**
     * 阿里云账号AccessKeySecret
     */
    private static String accessKeySecret = "hbRZeKyV3WaVAcTXOarOS9acfYdz4P";
    /**
     * 填写Bucket名称，例如examplebucket。
     */
    private static String bucketName = "edianzu-am";
    /**
     * 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
     */
//    static String objectName = "asset/asset_photo/202202/16456049474667a6e9.jpeg";
    private static String objectName = "asset/asset_photo/202202/00.jpeg";

    private static OSS ossClient = null;

    private static void init() {
        // 创建ClientConfiguration实例，您可以根据实际情况修改默认参数。
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        // 设置是否支持CNAME。CNAME用于将自定义域名绑定到目标Bucket
        conf.setSupportCname(true);

        // 创建OSSClient实例。
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);
    }

    private static void shutdown() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    public static boolean isExist() {
        return execute(new OssFunction<Boolean>() {
            @Override
            public Boolean run() {
                return ossClient.doesObjectExist(bucketName, objectName);
            }
        });
    }

    /**
     * 上传本地文件
     *
     * @param localPath 本地绝对路径 D:\\localpath\\examplefile.txt
     */
    public static void uploadLocalFile(String localPath) {
        execute(new OssFunction<Object>() {
            @Override
            public Object run() {
                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(localPath);
                } catch (Exception e) {
                    logger.error("流处理异常：{}", localPath, e);
                }
                ossClient.putObject(bucketName, objectName, inputStream);
                return null;
            }
        });
    }

    @FunctionalInterface
    public interface OssFunction<T> {
        T run();
    }

    private static <T> T execute(OssFunction<T> function){
        init();
        T run = function.run();
        shutdown();
        return run;
    }

    public static void main(String[] args) {
        System.out.println(isExist());

//        uploadLocalFile("D:\\易盘点系统维护资料\\oss备份\\20220323\\11.jpeg");
    }

}
